import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入全局样式表
import '../assets/css/global.css'

const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Home.vue')
const Welcome = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Welcome.vue')

const Users = () => import(/* webpackChunkName: "users" */ '@/components/User/Users.vue')

const Rights = () => import(/* webpackChunkName: "rights_roles" */ '@/components/power/Rights.vue')
const Roles = () => import(/* webpackChunkName: "rights_roles" */ '@/components/power/Roles.vue')

const Category = () => import(/* webpackChunkName: "goods" */ '@/components/goods/Category.vue')
const Params = () => import(/* webpackChunkName: "goods" */ '@/components/goods/Params.vue')
const GoodsList = () => import(/* webpackChunkName: "goods" */ '@/components/goods/GoodsList.vue')
const AddGoods = () => import(/* webpackChunkName: "goods" */ '@/components/goods/AddGoods.vue')

const OrderList = () => import(/* webpackChunkName: "order" */ '@/components/order/OrderList.vue')

const Reports = () => import(/* webpackChunkName: "reports" */ '@/components/reports/Reports.vue')

Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  // 路由重定向
  // 配置路由规则
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      // 不是标准写法，后期修改
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/addgood', component: AddGoods },
      { path: '/orders', component: OrderList },
      { path: '/reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫 在正式进入某一个路由之前进行判断token 来保证需要权限的页面的安全 再没有获取权限前无法通过地址进入
router.beforeEach((to, from, next) => {
  // to -- 要跳转的地址
  // from -- 从哪里页面跳转过来的
  // next -- 放行，执行下一步操作，或者强制跳转到某一个路由
  if (to.path === '/login') return next()
  // 判断要跳转的页面是否为login
  // 获取token 没有则为null 表示没有登录
  const myToken = window.sessionStorage.getItem('token')
  // 判断token是否存在 如果存在说明已经登录了，直接放行跳转 如果不存在强制跳转到login
  if (!myToken) return next('/login')
  next()
})

export default router
